package com.mofang.powerdekorhelper.persenter;

import com.mofang.powerdekorhelper.model.AppVersion;
import com.mofang.powerdekorhelper.utils.UrlTools;
import com.mofang.powerdekorhelper.utils.http.InitRetrofit;
import com.mofang.powerdekorhelper.utils.http.RetrofitSerives;
import com.mofang.powerdekorhelper.view.VersionUpdataView;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by luofei on 2017/9/20 0020.
 * 说明：
 */

public class VersionUpdataPersenter {

    RetrofitSerives requestSerives;
    Call<AppVersion> appVersionCall;
    VersionUpdataView view;

    public void getAppVersion(final VersionUpdataView view, int appId) {

        JSONObject object = new JSONObject();
        try {
            object.put("appID", appId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        final String requestStr = object.toString();

        requestSerives = InitRetrofit.getInstance().getRetrofit(UrlTools.AppUpdateUrl);

        final RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), requestStr);

        appVersionCall = requestSerives.getAppVersion(body);

        appVersionCall.enqueue(new Callback<AppVersion>() {
            @Override
            public void onResponse(Call<AppVersion> call, Response<AppVersion> response) {
                if (response.isSuccessful()) {
                    view.setVersionUpdata(response.body());
                } else {
                    view.OnError("获取新版本失败，稍候再试");
                }
            }

            @Override
            public void onFailure(Call<AppVersion> call, Throwable t) {
                view.OnError("获取新版本失败，稍候再试");
            }
        });

    }
}
